package com.zheng.api.server.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.zheng.api.common.constant.ApiConstant;
import com.zheng.api.common.constant.ApiResult;
import com.zheng.api.common.constant.ApiResultConstant;
import com.zheng.api.server.constant.WeChatConfigure;
import com.zheng.api.server.domain.CaptchaVerifyParam;
import com.zheng.api.server.service.base.um.Base4UmbrellaService;
import com.zheng.business.dao.model.BusinessOrderUmbrellaTimecard;
import com.zheng.business.dao.model.BusinessOrderUmbrellaTimecard;
import com.zheng.business.dao.model.BusinessOrderUmbrellaTimecardExample;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaTimecardService;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.*;
import com.zheng.umbrella.dao.model.UmbrellaHardwareMachine;
import com.zheng.umbrella.dao.model.UmbrellaRuleTimecardExample;
import com.zheng.umbrella.rpc.api.UmbrellaRuleTimecardService;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import com.zheng.wechat.mp.dao.model.*;
import com.zheng.wechat.mp.rpc.api.WechatMpGzuserService;
import com.zheng.wechat.mp.rpc.api.WechatMpNoticeService;
import com.zheng.wechat.mp.rpc.api.WechatMpSystemAccountService;
import com.zheng.wechat.mp.rpc.api.WechatMpWebJwidService;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.*;

/**
 * Created by lvb.
 * 小程序接口服务
 */
@Service("apiServerWechatAppService")
public class ApiServerWechatAppService extends Base4UmbrellaService{

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ApiServerWechatAppService.class);

    @Autowired
    ApiServerPayService apiServerPayService;
    @Autowired
    WechatMpGzuserService wechatMpGzuserService;
    @Autowired
    ApiServerCaptchaService apiServerCaptchaService;
    @Autowired
    WechatMpSystemAccountService wechatMpSystemAccountService;
    @Autowired
    UpmsSystemParamService upmsSystemParamService;
    @Autowired
    Base4UmbrellaService base4UmbrellaService;
    @Autowired
    UmbrellaRuleTimecardService umbrellaRuleTimecardService;
    @Autowired
    WechatMpNoticeService wechatMpNoticeService;

    @Autowired
    BusinessOrderUmbrellaTimecardService businessOrderUmbrellaTimecardService;
    @Autowired
    private WechatMpWebJwidService wechatMpWebJwidService;

    /**
     * 缓存模块前缀
     */
    @Value("${Redis.CacheModule}")
    private String cacheModule;


    /**
     *  超时门限(秒)
     */
    private static Integer EXPIRE_TIME = 60 * 60 * 24;

    public ApiResult login(String code,String rawData,String signature,String encryptedData,String iv,String ipAddress,String machineCode,String jwid) {
        LOGGER.info( "Start get SessionKey" );
        //LOGGER.info("签名"+signature);
        //LOGGER.info("用户非敏感信息"+rawData);

        ApiResult result = null;
        JSONObject dataInfo = new JSONObject();
        WechatMpGzuser wechatMpGzuser = null;
        WechatMpSystemAccount wechatMpSystemAccount = null;
        try {

            //动态获取appId及secret
            String reqAppId = "";
            String reqSecret = "";
            Integer userAgentId = Constant.CONST_SUPER_AGENTID;
            if(StringUtil.isNotEmpty(jwid)){
                WechatMpWebJwidExample wechatMpWebJwidExample = new WechatMpWebJwidExample();
                wechatMpWebJwidExample.createCriteria().andJwidEqualTo(jwid).andAccountTypeEqualTo("3");
                WechatMpWebJwid wechatMpWebJwid = wechatMpWebJwidService.selectFirstByExample(wechatMpWebJwidExample);
                if(wechatMpWebJwid!=null){
                    userAgentId = wechatMpWebJwid.getAgentId();
                    reqAppId = wechatMpWebJwid.getWeixinAppid();
                    reqSecret = wechatMpWebJwid.getWeixinAppsecret();
                }else{
                    jwid = WeChatConfigure.WECHATAPP_GH;
                    reqAppId = WeChatConfigure.WECHATAPP_APP_ID ;
                    reqSecret = WeChatConfigure.WECHATAPP_APP_SECRET;
                }
            }else{
                jwid = WeChatConfigure.WECHATAPP_GH;
                reqAppId = WeChatConfigure.WECHATAPP_APP_ID ;
                reqSecret = WeChatConfigure.WECHATAPP_APP_SECRET;
            }

            //根据code向腾讯服务器校验
            String url = WeChatConfigure.JSCODE2SESSION_URL + reqAppId + "&secret=" + reqSecret + "&js_code=" + code + "&grant_type=authorization_code";
            String callRet = PayCommonUtil.call4Post(url);
            if(StringUtil.isNotEmpty(callRet)){
                //解析校验数据
                //LOGGER.info("post请求获取的SessionAndopenId=" + callRet);
                JSONObject sessionKeyOpenIdJson = JsonUtil.getJSONObjectFromJson(callRet);
                String openid = sessionKeyOpenIdJson.getString("openid");
                String sessionKey = sessionKeyOpenIdJson.getString("session_key");
                String unionid = sessionKeyOpenIdJson.getString("unionid");
                //LOGGER.info("openid=" + openid + ",session_key=" + sessionKey);

                //把token、sessionKey和openid返回给小程序
                JSONObject encryptedJson = encryptedDataInfo(encryptedData, sessionKey, iv);
                dataInfo.put("encryptedData",encryptedJson);
                //LOGGER.info("根据解密算法获取的dataInfo=" + dataInfo);

                WechatMpGzuserExample example = new WechatMpGzuserExample();
                WechatMpGzuserExample.Criteria criteria = example.createCriteria();
                List<WechatMpGzuser> wechatMpGzuserList = null;
                //查询用户
                if(unionid!=null) {
                    //criteria.andOpenidEqualTo(openid);
                    criteria.andUnionidEqualTo(unionid);
                    criteria.andJwidEqualTo(jwid);
                    wechatMpGzuserList = wechatMpGzuserService.selectByExample(example);
                    wechatMpGzuser = CollectionUtils.isEmpty(wechatMpGzuserList) ? null : wechatMpGzuserList.get(0);
                }
                //查不到用户，使用openid查询
                if (wechatMpGzuser == null && openid !=null ) {
                    example = new WechatMpGzuserExample();
                    //清除条件
                    example.clear();
                    criteria = example.createCriteria();
                    criteria.andOpenidEqualTo(openid);
                    criteria.andJwidEqualTo(jwid);
                    wechatMpGzuserList = wechatMpGzuserService.selectByExample(example);
                    wechatMpGzuser = CollectionUtils.isEmpty(wechatMpGzuserList) ? null : wechatMpGzuserList.get(0);
                }

                UmbrellaHardwareMachine machine= null;
                if(StringUtils.isNotEmpty(machineCode)){
                    machine = base4UmbrellaService.baseSelectUmbrellaHardwareMachineNoCache(machineCode);
                }
                //用户不存在，新增
                if (wechatMpGzuser == null) {
                    //新增用户
                    //JSONObject rawDataJson = JsonUtil.getJSONObjectFromJson(rawData);
                    String nickName = encryptedJson.getString("nickName");
                    String avatarUrl = encryptedJson.getString("avatarUrl");
                    String gender = encryptedJson.getString("gender");
                    String city = encryptedJson.getString("city");
                    String country = encryptedJson.getString("country");
                    String province = encryptedJson.getString("province");

                    WechatMpGzuser insertUser = new WechatMpGzuser();
                    insertUser.setUnionid(unionid);
                    insertUser.setOpenid(openid);
                    insertUser.setNickname(nickName);
                    insertUser.setNicknameTxt(nickName);
                    insertUser.setHeadimgurl(avatarUrl);
                    insertUser.setCountry(country);
                    insertUser.setProvince(province);
                    insertUser.setCity(city);
                    insertUser.setSex(gender);
                    insertUser.setCreateTime(DateUtil.getNowDate());
                    insertUser.setManage(Constant.CONST_NO);
                    insertUser.setUserstatus(Constant.CONST_YES);
                    insertUser.setJwid(jwid);
                    //增加代理
                    if(machine!=null && machine.getAgentId()!=null) {
                        insertUser.setUserAgentId(machine.getAgentId());
                    }else{
                        insertUser.setUserAgentId(userAgentId);
                    }
                    //保存
                    wechatMpGzuserService.insert(insertUser);

                    //重新获取最新用户信息
                    wechatMpGzuserList = wechatMpGzuserService.selectByExample(example);
                    wechatMpGzuser = CollectionUtils.isEmpty(wechatMpGzuserList) ? null : wechatMpGzuserList.get(0);

                    //新增用户账号余额数据
                    WechatMpSystemAccount insertAcount = new WechatMpSystemAccount();
                    insertAcount.setUserId(wechatMpGzuser.getId());
                    //余额
                    insertAcount.setAmount(new BigDecimal(0));
                    //预付金
                    insertAcount.setDeposit(new BigDecimal(0));
                    //借伞数量
                    insertAcount.setUmbrellanumber(0);
                    insertAcount.setCreateBy("system");
                    insertAcount.setStatus(String.valueOf(Constant.CONST_YES));
                    insertAcount.setCreateTime(DateUtil.getNowDate());
                    //保存
                    wechatMpSystemAccountService.insert(insertAcount);

                    //查询用户账户信息
                    WechatMpSystemAccountExample accountExample = new WechatMpSystemAccountExample();
                    WechatMpSystemAccountExample.Criteria accountCriteria = accountExample.createCriteria();
                    accountCriteria.andUserIdEqualTo(wechatMpGzuser.getId());
                    List<WechatMpSystemAccount> wechatMpSystemAccountList = wechatMpSystemAccountService.selectByExample(accountExample);
                    wechatMpSystemAccount = CollectionUtils.isEmpty(wechatMpSystemAccountList) ? null : wechatMpSystemAccountList.get(0);

                } else {
                    //更新用户
                    //JSONObject rawDataJson = JsonUtil.getJSONObjectFromJson(rawData);
                    String nickName = encryptedJson.getString("nickName");
                    String avatarUrl = encryptedJson.getString("avatarUrl");
                    String gender = encryptedJson.getString("gender");
                    String city = encryptedJson.getString("city");
                    String country = encryptedJson.getString("country");
                    String province = encryptedJson.getString("province");

                    WechatMpGzuser updateUser = new WechatMpGzuser();
                    updateUser.setNickname(nickName);
                    updateUser.setNicknameTxt(nickName);
                    updateUser.setHeadimgurl(avatarUrl);
                    updateUser.setCountry(country);
                    updateUser.setProvince(province);
                    updateUser.setCity(city);
                    updateUser.setSex(gender);
                    updateUser.setOpenid(openid);
                    updateUser.setUnionid(unionid);
                    //更新代理
                    if(machine!=null && machine.getAgentId()!=null) {
                        updateUser.setUserAgentId(machine.getAgentId());
                    }else{
                        //这里一定要判断原来用户归属代理是否为null，为null才赋值为默认超级代理
                        if(wechatMpGzuser.getUserAgentId()==null){
                            updateUser.setUserAgentId(userAgentId);
                        }
                    }
                    //更新保存
                    WechatMpGzuserExample updateExample = new WechatMpGzuserExample();
                    WechatMpGzuserExample.Criteria updateCriteria = updateExample.createCriteria();
                    //updateCriteria.andOpenidEqualTo(openid);
                    updateCriteria.andIdEqualTo(wechatMpGzuser.getId());
                    wechatMpGzuserService.updateByExampleSelective(updateUser, updateExample);

                    //重新获取最新用户信息

                    //查询用户
                    wechatMpGzuserList = wechatMpGzuserService.selectByExample(example);
                    wechatMpGzuser = CollectionUtils.isEmpty(wechatMpGzuserList) ? null : wechatMpGzuserList.get(0);

                    //查询用户账户信息
                    WechatMpSystemAccountExample accountExample = new WechatMpSystemAccountExample();
                    WechatMpSystemAccountExample.Criteria accountCriteria = accountExample.createCriteria();
                    accountCriteria.andUserIdEqualTo(wechatMpGzuser.getId());
                    List<WechatMpSystemAccount> wechatMpSystemAccountList = wechatMpSystemAccountService.selectByExample(accountExample);
                    wechatMpSystemAccount = CollectionUtils.isEmpty(wechatMpSystemAccountList) ? null : wechatMpSystemAccountList.get(0);

                    Date nowDate = DateUtil.getDate();
                    boolean isDifference = false;
                    try{
                        isDifference = "true".equals(upmsSystemParamService.querySystemParamValueByParam_key("BUSINESS_ORDER_TIMECARD_SETTLE_DIFF_AGENT"));
                    }catch(Exception e){}
                    BusinessOrderUmbrellaTimecard latestTimeCard = super.baseSelectLastBusinessOrderUmbrellaTimecardNoCache(wechatMpGzuser.getId(),wechatMpGzuser.getUserAgentId(),isDifference);
                    //已购买时长卡还没到期
                    if(latestTimeCard!=null && latestTimeCard.getCardAfterEndtime()!=null && latestTimeCard.getCardAfterEndtime().after(nowDate)){
                        wechatMpSystemAccount.setCardType(latestTimeCard.getCardtype());
                        wechatMpSystemAccount.setCardBegintime(latestTimeCard.getCardAfterBegintime());
                        wechatMpSystemAccount.setCardEndtime(latestTimeCard.getCardAfterEndtime());
                        wechatMpSystemAccount.setCardFirsttime(latestTimeCard.getCardFirsttime());
                    }else{
                        wechatMpSystemAccount.setCardType(null);
                        wechatMpSystemAccount.setCardBegintime(null);
                        wechatMpSystemAccount.setCardEndtime(null);
                    }
                }

                //根据openid查询skey是否存在
                String skeyPath = cacheModule + ":" + ApiConstant.WECHATAPP_LOGIN_USER_TOKEN + ":" + wechatMpGzuser.getId();
                String skey_redis = RedisUtil.get(skeyPath);
                if (!StringUtil.isEmpty(skey_redis)) {
                    //存在 删除 skey 重新生成skey 将skey返回
                    RedisUtil.remove(skeyPath);

                }

                WechatMpSystemAccountExample accountExample = new WechatMpSystemAccountExample();
                accountExample.createCriteria().andUserIdEqualTo(wechatMpGzuser.getId());
                wechatMpSystemAccount = wechatMpSystemAccountService.selectFirstByExample(accountExample);

                //uuid生成唯一key并缓存
                String uuid = UUID.randomUUID().toString();
                RedisUtil.set(skeyPath, uuid, EXPIRE_TIME);
                //使用用户id加密token
                String encryptToken = XXTEAUtil.encrypt(uuid, wechatMpGzuser.getId().toString());

                boolean isUseTimeCard = false;
                //判断用户所属代理是否启用年卡
                if( wechatMpGzuser !=null && wechatMpGzuser.getUserAgentId()!=null ) {
                    UmbrellaRuleTimecardExample timecardExample = new UmbrellaRuleTimecardExample();
                    UmbrellaRuleTimecardExample.Criteria timecardCriteria = timecardExample.createCriteria();
                    //未删除
                    timecardCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
                    timecardCriteria.andAgentIdEqualTo(wechatMpGzuser.getUserAgentId());
                    timecardCriteria.andStatusEqualTo(Constant.CONST_ENABLE);
                    //有效期范围内的
                    Long time = new Date().getTime();
                    timecardCriteria.andBeginTimeLessThanOrEqualTo(time);
                    timecardCriteria.andEndTimeGreaterThanOrEqualTo(time);
                    //按类型排序
                    timecardExample.setOrderByClause(" cardtype asc ");
                    int count = umbrellaRuleTimecardService.countByExample(timecardExample);
                    isUseTimeCard = count > 0;
                }

                dataInfo.put("openId", openid);
                dataInfo.put("token", encryptToken);
                dataInfo.put("user", JsonUtil.getJSONObjectFromObj(wechatMpGzuser));
                dataInfo.put("userAccount", JsonUtil.getJSONObjectFromObj(wechatMpSystemAccount));
                //植入基本配置数据
                JSONObject configInfo = new JSONObject();
                configInfo.put("mqttUrl",upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_WECHATAPP_COMM_MQTTURL"));
                configInfo.put("mqttUserName",upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_WECHATAPP_COMM_MQTTUSERNAME"));
                configInfo.put("mqttPassword",upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_WECHATAPP_COMM_MQTTPASSWORD"));
                configInfo.put("topic",upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_WECHATAPP_COMM_TOPIC"));
                configInfo.put("queue",upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_WECHATAPP_COMM_QUEUE"));
                configInfo.put("manageTimeout",upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_MAINTAINTIMEOUT"));
                configInfo.put("businessTimeout",upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_BUSINESSTIMEOUT"));
                dataInfo.put("configInfo", configInfo);
                dataInfo.put("isUseTimeCard", isUseTimeCard);

          }else{
                result = new ApiResult(ApiResultConstant.FAILED.code,"访问微信服务器校验失败",null,null,dataInfo);
            }
        }catch(Exception e){
            LOGGER.error("登陆失败",e);
            e.getStackTrace();
            result = new ApiResult(ApiResultConstant.FAILED.code,"登陆失败",null,null,dataInfo);
        }

        result = new ApiResult(ApiResultConstant.SUCCESS.code,"登陆成功",null,null,dataInfo);

        return result;
    }

    public ApiResult bindMobile(String code,String rawData,String signature,String encryptedData,String iv,String ipAddress) {
        //LOGGER.info("签名"+signature);
        //LOGGER.info("用户非敏感信息"+rawData);

        ApiResult result = null;
        JSONObject dataInfo = null;
        try {
            //根据code向腾讯服务器校验
            String url = WeChatConfigure.JSCODE2SESSION_URL + WeChatConfigure.WECHAT_APP_ID + "&secret=" + WeChatConfigure.WECHAT_APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
            String callRet = PayCommonUtil.call4Post(url);
            //解析校验数据
            //LOGGER.info("post请求获取的SessionAndopenId=" + callRet);
            JSONObject sessionKeyOpenIdJson = JsonUtil.getJSONObjectFromJson(callRet);
            String openid = sessionKeyOpenIdJson.getString("openid");
            String sessionKey = sessionKeyOpenIdJson.getString("session_key");
            String unionid = sessionKeyOpenIdJson.getString("unionid");
            //LOGGER.info("openid=" + openid + ",session_key=" + sessionKey);
            //查询用户
            WechatMpGzuserExample example = new WechatMpGzuserExample();
            WechatMpGzuserExample.Criteria criteria = example.createCriteria();
            criteria.andOpenidEqualTo(openid);
            List<WechatMpGzuser> wechatMpGzuserList = wechatMpGzuserService.selectByExample(example);
            WechatMpGzuser wechatMpGzuser = CollectionUtils.isEmpty(wechatMpGzuserList) ? null : wechatMpGzuserList.get(0);
            //用户不存在
            if (wechatMpGzuser == null) {
                result = new ApiResult(ApiResultConstant.FAILED.code,"绑定手机失败",null,null,dataInfo);
            } else {
                /**
                    {
                        "phoneNumber": "13580006666",     //用户绑定的手机号（国外手机号会有区号）
                        "purePhoneNumber": "13580006666", //没有区号的手机号
                        "countryCode": "86",              //区号
                        "watermark":
                        {
                            "appid":"APPID",
                            "timestamp":TIMESTAMP
                        }
                    }
                 */
                dataInfo = encryptedDataInfo(encryptedData, sessionKey, iv);
                //LOGGER.info("根据解密算法获取的dataInfo=" + dataInfo);
                dataInfo.put("userDetail", JsonUtil.getJSONObjectFromObj(wechatMpGzuser));
                //更新保存
                WechatMpGzuser updateUser = new WechatMpGzuser();
                updateUser.setMobile(dataInfo.getString("purePhoneNumber"));
                WechatMpGzuserExample updateExample = new WechatMpGzuserExample();
                WechatMpGzuserExample.Criteria updateCriteria = updateExample.createCriteria();
                updateCriteria.andOpenidEqualTo(openid);
                wechatMpGzuserService.updateByExampleSelective(updateUser, updateExample);

                //把token、sessionKey和openid返回给小程序
                wechatMpGzuser.setMobile(dataInfo.getString("purePhoneNumber"));
                dataInfo.put("mobile", dataInfo.getString("purePhoneNumber"));
                dataInfo.put("userDetail", JsonUtil.getJSONObjectFromObj(wechatMpGzuser));
            }
        }catch(Exception e){
            LOGGER.error("绑定手机失败",e.getStackTrace());
            result = new ApiResult(ApiResultConstant.FAILED.code,"绑定手机失败",null,null,dataInfo);
        }
        result = new ApiResult(ApiResultConstant.SUCCESS.code,"绑定手机成功",null,null,dataInfo);

        return result;
    }

    private JSONObject encryptedDataInfo(String encryptedData,String sessionKey,String iv){
        // 被加密的数据
        byte[] dataByte = Base64Util.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64Util.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64Util.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init( Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JsonUtil.getJSONObjectFromJson(result);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    public boolean verificationCode(String mobileNo, String verificationCode, Map<String, Object> result,String CodeType) {
        boolean tokenRet = false;
        try {
            CaptchaVerifyParam param = new CaptchaVerifyParam();
            param.setKey(mobileNo);
            param.setCaptcha(verificationCode);
            tokenRet = apiServerCaptchaService.doVerify(param);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LOGGER.error("验证码验证出错",e);
            result.put("message", e.getMessage());
            return true;
        }
        if (!tokenRet) {
            result.put("success", false);
            result.put("message", "验证码不正确");
            return true;
        }
        return false;
    }

    /**
     * 根据用户ID获取用户账号余额信息
     * @param userId
     * @return
     */
    public WechatMpSystemAccount getUserAccountByUserId(Integer userId,String machineCode) {

        WechatMpSystemAccountExample accountExample = new WechatMpSystemAccountExample();
        accountExample.createCriteria().andUserIdEqualTo(userId);
        WechatMpSystemAccount wechatMpSystemAccount =  wechatMpSystemAccountService.selectFirstByExample(accountExample);

        if(wechatMpSystemAccount!=null) {
            UmbrellaHardwareMachine machine = null;
            Integer userAgentId = null;
            if (StringUtils.isNotEmpty(machineCode)) {
                machine = base4UmbrellaService.baseSelectUmbrellaHardwareMachineNoCache(machineCode);
                if (machine != null) {
                    userAgentId = machine.getAgentId();
                }
            }
            if (userAgentId == null) {
                WechatMpGzuser wechatMpGzuser = super.baseSelectWechatMpGzuser(userId, false);
                if (wechatMpGzuser != null) {
                    userAgentId = wechatMpGzuser.getUserAgentId();
                    if(userAgentId==null){
                        userAgentId = Constant.CONST_SUPER_AGENTID;
                    }
                }
            }
            Date nowDate = DateUtil.getDate();
            boolean isDifference = false;
            try{
                isDifference = "true".equals(upmsSystemParamService.querySystemParamValueByParam_key("BUSINESS_ORDER_TIMECARD_SETTLE_DIFF_AGENT"));
            }catch(Exception e){}
            BusinessOrderUmbrellaTimecard latestTimeCard = super.baseSelectLastBusinessOrderUmbrellaTimecardNoCache(userId, userAgentId,isDifference);
            //已购买时长卡还没到期
            if (latestTimeCard != null && latestTimeCard.getCardAfterEndtime() != null && latestTimeCard.getCardAfterEndtime().after(nowDate)) {
                wechatMpSystemAccount.setCardType(latestTimeCard.getCardtype());
                wechatMpSystemAccount.setCardBegintime(latestTimeCard.getCardAfterBegintime());
                wechatMpSystemAccount.setCardEndtime(latestTimeCard.getCardAfterEndtime());
                wechatMpSystemAccount.setCardFirsttime(latestTimeCard.getCardFirsttime());
            } else {
                wechatMpSystemAccount.setCardType(null);
                wechatMpSystemAccount.setCardBegintime(null);
                wechatMpSystemAccount.setCardEndtime(null);
            }
        }
        return wechatMpSystemAccount;
    }

    public List<WechatMpNotice> getNoticetMessage() {
        long time = System.currentTimeMillis();
        WechatMpNoticeExample example = new WechatMpNoticeExample();
        WechatMpNoticeExample.Criteria criteria = example.createCriteria();
        Integer STATUS_NORMAL = 1;
        criteria.andStatusEqualTo(STATUS_NORMAL.byteValue());//正常状态
        criteria.andBeginTimeLessThan(time);
        criteria.andEndTimeGreaterThan(time);
        example.setOrderByClause(" orders asc");
        return wechatMpNoticeService.selectByExample(example);
    }
}
